import React, {Component} from 'react';
import { history, connect } from 'umi'
import { ArrowLeftOutlined } from '@ant-design/icons'
import {
  Card,
  Button,
  Form,
  Input,
  Cascader,
  message
} from "antd";

import { reqCategorys } from '../category/service'
import PicturesWall from './component/PicturesWall'
import RichTextEditor from './component/RichTextEditor'

const { TextArea } = Input;
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 6 },
};

class AddUpdate extends Component {

  state = {
    options: [], // 初始化级联列表一级分类列表
  }

  // 表单验证价格
  validatePrice = (rule, value, callback) => {
    if (Number(value) > 0) {
      // 验证通过
      callback()
    }else {
      // 验证没通过
      callback('价格必须大于0')
    }
  }

  initOptions = async (categorys) => {
    // 根据categorys生成options数组 一级分类列表options
    const options = categorys.map((item) => ({
      value: item._id,
      label: item.name,
      isLeaf: false,
    }))
    // 如果是一个二级分类列表下的更新
    const { product: { categoryId, pCategoryId } , isUpdate } = this.props
    // const { categoryId, pCategoryId } = product
    if (isUpdate && pCategoryId !== '0') {
      const subCategorys = await this.getCategorys(pCategoryId)
      const childOption = subCategorys.map(item => ({
        value: item._id,
        label: item.name,
        isLeaf: true,
      }))
      // 找到当前商品对应的一级options对象
      const targetOption = options.find(option => option.value === pCategoryId)
      // 添加到一级分类列表的children下
      targetOption.children = childOption
    }
    this.setState({options})
  };

  // 用于加载Cascader下一级的列表
  loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    // 根据选中的一级分类列表加载二级分类列表
    const subCategorys = await this.getCategorys(targetOption.value)
    targetOption.loading = false
    if (subCategorys && subCategorys.length > 0) {
      // 当前选中的分类有二级分类
      const childOption = subCategorys.map((item) => ({
        value: item._id,
        label: item.name,
        isLeaf: true,
      }))
      targetOption.children = childOption
    } else {
      // 当前选中的分类没有二级分类
      targetOption.isLeaf = true
    }
    this.setState({
      options: [...this.state.options]
    })
  };

  // 获取一级/二级分类列表 async返回的是一个新的promise
  getCategorys = async (parentId) => {
    try {
      const { status, data, msg } = await reqCategorys({
       payload: {
         params: {parentId}
       }
      })
      if (status === 0 ) {
        const categorys = data
        // 判断是否是一级分类列表
        if ( parentId === '0') {
          this.initOptions(categorys)
        }else {
          // 返回二级列表, async返回的是一个promise,返回的状态是成功且value为categorys
          return new Promise((resolve) => resolve(categorys))
        }

      }else {
        message.error(msg)
      }
    }catch (e) {
      console.log(e);
    }
  }

  // 提交表单事件回调
  onFinish = (value) => {
    // 1. 收集数据并封装成product对象
    const { dispatch, isUpdate, product: { _id }, detail, imgs } = this.props
    const { name, desc, price, categoryIds } = value
    // 判断当前是一级还是二级
    let pCategoryId, categoryId
    if (categoryIds.length === 1) { // 当前是一级分类
      pCategoryId = '0'
      categoryId = categoryIds[0]
    } else {
      pCategoryId = categoryIds[0]
      categoryId = categoryIds[1]
    }
    const newProduct = { pCategoryId, categoryId, name, desc, price, imgs ,detail }
    // 如果是更新, 添加_id
    if (isUpdate) {
      newProduct._id = _id
    }
    // console.log(newProduct);
    // 2. 调用接口请求函数去添加/修改数据
    dispatch({
      type: 'product/fetchAddOrUpdateProduct',
      payload: {
        ...newProduct
      },
      callback: (data) => {
        const { status, msg } = data
        if (status === 0) {
          message.success(`${isUpdate ? '更新' : '修改'}商品成功`)
          history.goBack()
        }else {
          message.error(msg)
        }
      }
    })
  }

  componentDidMount(): void {
    this.getCategorys('0')
  }

  render() {
    // console.log(this.props.location.state.product)
    const { options } = this.state
    const { isUpdate, product: { name, desc, price, categoryId, pCategoryId, detail }  } = this.props
    // const { name, desc, price, categoryId, pCategoryId, detail } = product || {}
    const categoryIds = []
    if (isUpdate) {
      if (pCategoryId === '0') {
        categoryIds.push(categoryId)
      }else {
        categoryIds.push(pCategoryId)
        categoryIds.push(categoryId)
      }
    }
    const title = (
      <>
        <Button
          onClick={
            () => history.goBack()
          }
          type="link"
        >
          <ArrowLeftOutlined style={{ fontSize: 20}} />
        </Button>
        <span style={{marginLeft: 5}}>{isUpdate ? '修改商品' : '添加商品'}</span>
      </>
    )

    return (
      <Card title={title}>
        <Form
          name="validate_other"
          {...layout}
          onFinish={this.onFinish}
          initialValues={{
            name ,
            desc,
            price,
            categoryIds,
          }}
        >
          <Form.Item
            name="name"
            label="商品名称:"
            rules={[
              {
                required: true,
                message: '请输入商品名称!',
              },
            ]}
          >
            <Input placeholder="请输入商品名称!" />
          </Form.Item>
          <Form.Item
            name="desc"
            label="商品描述:"
            rules={[
              {
                required: true,
                message: '请输入商品描述',
              },
            ]}
          >
            <TextArea placeholder="请输入商品描述!"/>
          </Form.Item>
          <Form.Item
            name="price"
            label="商品价格:"
            rules={[
              {
                required: true,
                message: '请输入商品描述',
              },
              {validator: this.validatePrice},
            ]}
          >
            <Input type="number" placeholder="请输入商品描述" addonAfter="元"/>
          </Form.Item>
          <Form.Item
            name="categoryIds"
            label="商品分类"
            hasFeedback
            rules={[{ required: true, message: '请输入商品分类!' }]}
          >
            <Cascader options={options} loadData={this.loadData} placeholder="请指定商品分类!" />
          </Form.Item>

          <Form.Item label="商品图片">
            <Form.Item name="imgs" noStyle>
              <PicturesWall
                // ref={this.picturesWall}
                // imgs={imgs}
              />
            </Form.Item>
          </Form.Item>

          <Form.Item label="商品详情" labelCol={{ span: 2 }} wrapperCol={{ span: 20 }}>
            <Form.Item name="detail" noStyle>
              <RichTextEditor
                // ref={this.detail}
                detail={detail}
              />
            </Form.Item>
          </Form.Item>

          <Form.Item wrapperCol={{ span: 4, offset: 3 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
    );
  }
}

export default connect(({ product }) => ({
  ...product
}))(AddUpdate);
